package com.zjdiepu.www.proxy.task;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.OpenCardStatus;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.consts.ThreadFactory;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.config.ScheduleProxyConfig;
import com.zjdiepu.www.diepu.biz.IDiepuProxyService;
import com.zjdiepu.www.diepu.biz.IQiniuProxySerive;
import com.zjdiepu.www.enums.TimedTaskStatus;
import com.zjdiepu.www.enums.TransferModeID;
import com.zjdiepu.www.hzicbc.biz.HzicbcBizApiService;
import com.zjdiepu.www.hzicbc.biz.IHzicbcProxyService;
import com.zjdiepu.www.proxy.biz.own.HzBiz;
import com.zjdiepu.www.proxy.biz.own.HzGhBiz;
import com.zjdiepu.www.proxy.biz.own.LogsBiz;
import com.zjdiepu.www.proxy.biz.transfer.INewTransaction;
import com.zjdiepu.www.proxy.biz.transfer.ITransferOtherTimedTaskService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOrdernoBankService;
import com.zjdiepu.www.proxy.dao.transfer.TransferOtherTimedTaskMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferZxQueryCreditApplySubMapper;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferOtherTimedTask;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferOtherTimedTaskExt;

@Component
public class OtherTimedTask {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private HzGhBiz hzGhBiz;
	
	@Resource
	private HzBiz hzBiz;
	
	@Resource
	private LogsBiz logsBiz;
	
	@Resource
	private ITransferOtherTimedTaskService transferOtherTimedTaskService; 
	
	@Resource
	private TransferOtherTimedTaskMapper transferOtherTimedTaskMapper;
	
	@Resource
	private IDiepuProxyService diepuProxyService;
	
	@Resource
	private IHzicbcProxyService hzicbcProxyService;
	
	@Resource
	private IQiniuProxySerive qiniuProxySerive;
	
	@Resource
	private HzicbcBizApiService hzicbcBizApiService;
	
	@Resource
	private ITransferYwOrdernoBankService transferYwOrdernoBankService;
	
	@Resource
	private TransferZxQueryCreditApplySubMapper transferZxQueryCreditApplySubMapper; 
	@Resource
	private INewTransaction newTransaction;
	@Resource
	protected ScheduleProxyConfig scheduleProxyConfig;
	
	/**
	 * 启动定时任务
	 */
	@Scheduled(fixedRateString = "${schedule.task.fixrate}", initialDelay = 0)
	private void runTask() {
		TransferOtherTimedTaskExt transferOtherTimedTaskExt=new TransferOtherTimedTaskExt();
		transferOtherTimedTaskExt.setBaseWhere();
		transferOtherTimedTaskExt.setTimedTaskStatus(10);  
		transferOtherTimedTaskExt.withOutPage();
		transferOtherTimedTaskExt.setOrderSql(" `TIIME_EXECUTE` ASC ");
		transferOtherTimedTaskExt.setWhereSql("`TIIME_EXECUTE` <= '" + DateUtil.dateTo14String(new Date()) + "'");
		List<TransferOtherTimedTask> transferOtherTimedTasks = transferOtherTimedTaskService.selectByExt(transferOtherTimedTaskExt);
		if(CollectionUtils.isNotEmpty(transferOtherTimedTasks)){
			for (TransferOtherTimedTask transferOtherTimedTask : transferOtherTimedTasks) {
				 try {
					ThreadFactory.THREAD_SERVICE.submit(() -> {
						saveStartTask(transferOtherTimedTask);
					});
				 } catch (Exception e) {
					 logger.error("start task happend exception.", e);
				 }
			}
		}
	}
	/**
	 * 执行单条任务
	 * @param transferOtherTimedTask
	 * @return
	 */
	private boolean saveStartTask(TransferOtherTimedTask transferOtherTimedTask) {
		boolean flag = true;
		String modeId;
		String orderno = transferOtherTimedTask.getBankOrderNo();
		modeId = transferOtherTimedTask.getModeID();
		String datasId = transferOtherTimedTask.getDataid();
		
		if(TransferModeID.TZKKCG.getCode().equals(modeId)) { /*向主程序通知开卡成功*/
			flag = diepuProxyService.saveNoticeOpenCardSuccess(datasId);
		} else if(TransferModeID.TZKKSB.getCode().equals(modeId)){ /*通知开卡失败*/
			flag=diepuProxyService.saveNoticeOpenCardFail(datasId,OpenCardStatus.KAI_KA_SHI_BAI.getCode(),"银行通知开卡失败");
		}else if(TransferModeID.CHA_XUN_KAI_KA_JIN_DU.getCode().equals(modeId)){//查询开卡进度
			flag=hzicbcProxyService.diepuQueryOpenCardCourse(modeId,datasId);
		}
		else if(TransferModeID.SQKK.getCode().equals(modeId)) { /*申请开卡*/
			try{
			flag = hzicbcProxyService.applyToIcbcOpenCard(modeId,datasId);
			if(!flag){
				diepuProxyService.saveNoticeOpenCardFail(datasId,OpenCardStatus.JIE_KOU_TUI_HUI.getCode(),"接口退回");
			}else{
				newTransaction.queryOpenCardCourse(orderno, datasId, DateUtil.increaseMinute(new Date(), scheduleProxyConfig.getOpenCardStatus() / 1000 / 60));
			}
			}catch(Exception e) {
				e.printStackTrace();
			}
		} else if(TransferModeID.CXFQZT.getCode().equals(modeId))  { /*向工行查询分期状态*/
			flag = hzicbcProxyService.saveApplyDiviStatus(orderno);
		} else if(TransferModeID.HQFJLB.getCode().equals(modeId)) { /*向主程序同步附件列表*/
			TransferYwOrdernoBank transferYwOrdernoBank = new TransferYwOrdernoBank();
			transferYwOrdernoBank.setOrdeRno(orderno);
			transferYwOrdernoBank.setDpStatus(DpStatus.NORMAL.getCode());
			transferYwOrdernoBank.setOrderSql("`CREATED` DESC");
			transferYwOrdernoBank = transferYwOrdernoBankService.selectRefined(transferYwOrdernoBank);
			if(null != transferYwOrdernoBank && StringUtils.isNotBlank(transferYwOrdernoBank.getQueryCreditApplyId())) {
				diepuProxyService.saveTransferOtherAttachments(transferYwOrdernoBank.getQueryCreditApplyId(), orderno);
			}
			flag = diepuProxyService.saveTransferOtherAttachments(datasId, orderno);
		} else if(TransferModeID.XZFJ.getCode().equals(modeId)) { /*向七牛同步七牛文件*/
			flag = qiniuProxySerive.downloadFile(orderno);
		} else if(TransferModeID.SQCZX.getCode().equals(modeId)) { //提交征信数据
			try {
				flag = hzicbcBizApiService.creditTask(orderno, datasId, modeId);
			} catch (Exception e) {
				logger.error("credit task happend exception.", e);
				transferOtherTimedTask.setTimedTaskStatus(TimedTaskStatus.ZHI_XIN_SHI_BAI.getCode());
			}
		} else if(TransferModeID.SQFQ.getCode().equals(modeId))  { /*向工行申请工行分期*/
			flag = hzicbcProxyService.saveApplyDivi(orderno);
		} else if(TransferModeID.M_TRANSFER_XZMQFJ.getCode().equals(modeId))  { /*容联云下载面签视频*/
			flag = hzicbcProxyService.downloadInterviewMedia(orderno, datasId);
		} else if(TransferModeID.TUI_SONG_MIAN_QIAN_SHI_PIN.getCode().equals(modeId))  { /*通用业务多媒体资料补充接口*/
			flag = hzicbcProxyService.multiMediaUpload(orderno, datasId);
		} else if(TransferModeID.GENG_XIN_MIAN_QIAN_FU_JIAN_TUI_SONG_ZHUANG_TAI.getCode().equals(modeId))  { /*中间服务器向主程序发送更新面签附件推送状态通知*/
			flag = hzicbcProxyService.saveSynPushStatus(orderno, datasId);
		}
		
		//更新任务状态
		transferOtherTimedTask.initUpdateData(SystemConsts.DEFAULT_ID, "定时任务执行完成");
		if(flag) {
			transferOtherTimedTask.setTimedTaskStatus(TimedTaskStatus.YI_ZHI_XING.getCode());
		} else {
			transferOtherTimedTask.setTimedTaskStatus(TimedTaskStatus.ZHI_XIN_SHI_BAI.getCode());
		}
		transferOtherTimedTaskMapper.updateByPrimaryKeySelective(transferOtherTimedTask);
		return flag;
	}
	
}
